package photogcalc.util;

/*
 * This is and should freely available for anyone as a Public Domain.
 *
 */

/** Formats decimal numbers.
 * 
 * @author Antti Okkonen
 * @version 2008-01-15
 */
public class Formatter {

    /** Format decimal number.
     *
     * @param value double value to format
     * @param decimals how many decimals are printed
     * @return formatted string
     */
    public static String format(double value, int decimals) {
        double tmp = 10;
        int prefixZeros = 0;
        boolean morePrefixZeros = true;
        boolean negativeNumber = (value < 0) ? true : false;

        if (Double.isInfinite(value) == false) {
            if (negativeNumber) {
                value *= -1;
            }

            for (int i = 0; i < decimals; i++) {
                tmp *= 10;
            }

            value += 5.0 / tmp;

            int intpart = (int) value;
            int decpart = 0;
            tmp = value - intpart;
            for (int i = 0; i < decimals; i++) {
                tmp *= 10;
                if (((int) tmp == 0) && morePrefixZeros) {
                    prefixZeros++;
                } else {
                    morePrefixZeros = false;
                }

                decpart += (int) tmp;
                decpart *= 10;
                tmp -= (int) tmp;
            }

            StringBuffer zeros = new StringBuffer("");
            for (int i = 0; i < prefixZeros; i++) {
                zeros.append("0");
            }

            decpart /= 10;

            if (negativeNumber) {
                intpart *= -1;
            }
            return intpart + "." + zeros.toString() + decpart;
        }
        else
            return "inf";
    }
}
